import {getRoles} from "@/utils/auth";
import {LOGICAL} from "@/constantData";
import {isArr} from "@/utils/arrayUtil";

const authentication = (authority) => {
  if (!authority) return false
  let {role: needPermissions, logical} = authority
  const allPermissionsArr = getRoles().split(',')
  if (logical == LOGICAL.AND) {
    return needPermissions.every(p => simpleMatch(allPermissionsArr, p))
  } else {
    return needPermissions.some(p => simpleMatch(allPermissionsArr, p))
  }
  return false
};

function simpleMatch(patterns, str) {
  if (isArr(patterns)) {
    for (let i = 0; i < patterns.length; i++) {
      if (simpleMatchHelper(patterns[i], str)) {
        return true;
      }
    }
  }
  return false;
}

function simpleMatchHelper(pattern, str) {
  if (pattern == null || str == null) {
    return false;
  }

  const firstIndex = pattern.indexOf('*');
  if (firstIndex === -1) {
    return pattern === str;
  }

  if (firstIndex === 0) {
    if (pattern.length === 1) {
      return true;
    }
    const nextIndex = pattern.indexOf('*', 1);
    if (nextIndex === -1) {
      return str.endsWith(pattern.substring(1));
    }
    const part = pattern.substring(1, nextIndex);
    if (part === '') {
      return simpleMatchHelper(pattern.substring(nextIndex), str);
    }
    let partIndex = str.indexOf(part);
    while (partIndex !== -1) {
      if (simpleMatchHelper(pattern.substring(nextIndex), str.substring(partIndex + part.length))) {
        return true;
      }
      partIndex = str.indexOf(part, partIndex + 1);
    }
    return false;
  }

  return (str.length >= firstIndex && pattern.startsWith(str.substring(0, firstIndex)) && simpleMatchHelper(pattern.substring(firstIndex), str.substring(firstIndex)));
}

export {authentication}
